const { adminInfo } = require('../config/config'), //修改
  { loginCheckInfo } = require('../services/AdminService'), //修改
  { makeCrypto, trimSpace, returnInfo, addProblemType } = require('../libs/utils'),
  errorInfo = require('../config/error_config'),
  { LOGIN } = errorInfo; //登录信息配置


//config
const pageConf = require('../config/config').pageConf;
const commonPageConf = require('../config/config').commonPageConf;

//service
const UserService = require('../services/User');
const ResolveRecordService = require('../services/ResolveRecord');
const ResolveListService = require('../services/ResolveList');
const LoginInfoService = require('../services/LoginInfo');
const RecommendListService = require('../services/RecommendList');
const ProblemService = require('../services/Problem');
const ProblemTypeService = require('../services/ProblemType');
const DataTableService = require('../services/DataTable');

//method
const recommendProblemTool = require('../libs/recomend');

//类型检测
function getAdvantageType() {
  return '基础题';
}

function getDisadvantageType() {
  return '数组';
}


class UserController {

  //注册页面
  async getRegister(ctx, next) {

    await ctx.render('register', {
      pageConf: pageConf.register
    })

  }

  //用户注册
  async createUser(ctx, next) {
    const userData = ctx.request.body;

    userData.password = makeCrypto(userData.password);

    const res = await UserService.addUser(userData);


    if (res[0] == 1) {
      ctx.body = {
        status: 200,
        msg: 'ok'
      }
      ctx.response.redirect('/user/login');
    } else {
      ctx.body = {
        status: 10003,
        msg: 'register fail'
      }
    }

  }

  //登录页面
  async getLoginPage(ctx, next) {
    await ctx.render('user/login', {});
  }

  //用户登录
  async loginAction(ctx, next) {
    const { uid, password } = ctx.request.body;

    if (!uid || !password) {
      ctx.body = returnInfo(LOGIN.INVALID_OPERATION); //非法操作
      return;
    }

    if (trimSpace(uid).length <= 0) {
      ctx.body = returnInfo(LOGIN.INVALID_USERNAME_LENGTH);
      return;
    }

    if (trimSpace(password).length <= 0) {
      ctx.body = returnInfo(LOGIN.INVALID_PASSWORD_LENGTH);
      return;
    }

    //组合用户信息，同时用md5加密密码
    const userInfo = {
      uid: trimSpace(uid),
      password: makeCrypto(trimSpace(password))
    }

    //检查
    const result = await UserService.loginCheckInfo(userInfo);

    if (result === 10003) {
      ctx.body = returnInfo(LOGIN.USERNAME_NOT_EXIST);
      return;
    }

    if (result === 10004) {
      ctx.body = returnInfo(LOGIN.PASSWORD_ERROR);
      return;
    }

    if (!ctx.session.userInfo) {
      //检查session， 初次登录为undefined，设置
      ctx.session.userInfo = result;
    }

    //添加登录记录
    const dateStr = new Date().toString(),
      sessionUserInfo = ctx.session.userInfo;

    const loginInfo = {
      uid: sessionUserInfo.uid,
      login_time: dateStr,
      userId: sessionUserInfo.id
    }

    const res = LoginInfoService.addLoginInfo(loginInfo)

    ctx.body = returnInfo(LOGIN.SUCCESS, sessionUserInfo); //返回成功code和用户信息
    ctx.response.redirect('/index');
  }


  //检查登录
  async loginCheck(ctx, next) {
    //满足条件
    if (ctx.session && ctx.session.userInfo) {
      ctx.body = returnInfo(LOGIN.LOGIN_STATUS);
      return;
    }

    //非登录状态
    ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS);
  }


  //登出
  async logoutAction(ctx, next) {
    delete ctx.session.userInfo;
    ctx.body = returnInfo(LOGIN.LOGOUT_SUCCESS);
  }


  //用户作答
  //start
  async submitProblemAnswer(ctx, next) {
    const answer = ctx.request.body;
    let { problem_answer, submit_result, problemTypeId, pid, problemId } = answer;

    //1.创建答题记录 只保留一条
    const userId = ctx.session.userInfo.id;

    //创建或更新
    const res = ResolveRecordService.addResolveRecord({
      userId,
      problemTypeId,
      submit_code: problem_answer,
      submit_result,
      problemId,
      pid
    })

    //2.用户已解题列表

    if (submit_result == 1) {
      //查询
      const resolveListRes = await ResolveListService.findResolveListById(userId);

      if (!resolveListRes) {
        ResolveListService.addResolveList({
          userId,
          resolve_num: 1,
          resolve_list: '' + pid
        })
      } else {
        const newArr = [];
        let isExist = false;

        let resolveList = resolveListRes.get('resolve_list');
        let resolveNum = resolveListRes.get('resolve_num');

        //查重
        if (resolveNum == 1 && resolveList != pid) {
          resolveList = resolveList + ',' + pid;
          resolveNum = resolveNum + 1;
        } else {
          const resolveArr = resolveList.split(',');
          resolveArr.forEach(item => {
            item == pid && (isExist = true);
          })

          !isExist && resolveArr.push(pid);
          resolveList = resolveArr.join(',');
          resolveNum = resolveArr.length;
        }

        //保存
        ResolveListService.addResolveList({
          userId,
          resolve_num: resolveNum,
          resolve_list: resolveList
        })
      }
    }

    //3.用户信息添加
    //查询
    const userRes = await UserService.findUserById(userId);

    let submit_num = userRes.get('submit_num');
    let resolve_num = userRes.get('resolve_num');

    if (submit_result == '1') {
      resolve_num++;
      submit_num++;
    } else {
      submit_num++;
    }

    const userData = {
      resolve_num,
      submit_num
    }

    const userUpdate = await UserService.updateUser(userData, userId);

    ctx.body = {
      msg: 'ok'
    }
  }
  //end

  //推荐题目
  async recommendProblem(ctx, next) {

    const userId = ctx.session.userInfo.id;

    const recomListRes = await RecommendListService.findRecomListById(userId) || [];
    const recomListArr = recomListRes.get('recom_list').split(',');

    //组合推荐题目信息
    let recomProblemList = await ProblemService.findProblemByIdGroup(recomListArr);
    const problem_type = await ProblemTypeService.getAllProblemType();

    //错题列表
    const errListArr = (await RecommendListService.findRecomListById(ctx.session.userInfo.id)).get('error_problem_list').split(',');
    let errProblemList = await ProblemService.findProblemByIdGroup(errListArr);

    //错题列表添加type字段
    errProblemList = await addProblemType(errProblemList);
    recomProblemList = await addProblemType(recomProblemList);

    await ctx.render('user/recom_problem', {
      pageConf: pageConf.recom_problem,
      commonPageConf,
      problemList: recomProblemList,
      isLogin: ctx.session.userInfo ? true : false,
      curRouter: '/user/recom-problem',
      errProblemList
    })
  }

  //刷新每日推荐题目
  async refreshRecomProblem(ctx, next) {
    //生成新的推荐列表
    const recomProblemList = await recommendProblemTool(ctx) || [];

    //组合推荐题目信息
    const problem_type = await ProblemTypeService.getAllProblemType();

    // 添加type字段 problemTypeId ->  type
    const typeObj = {};

    problem_type.forEach((item, index) => {
      typeObj[item.id] = item.type_title;
    });

    recomProblemList.map((item, index) => {
      item.dataValues.type = typeObj[item.problemTypeId];
      return item;
    })

    ctx.body = {
      code: 0,
      problemList: recomProblemList
    }
  }

  //个人中心
  async getUserCenter(ctx, next) {
    //个人数据统计分析
    const userId = ctx.session.userInfo.id;

    //用户数据信息
    const userRes = await UserService.findUserById(userId);
    const dataTableRes = await DataTableService.getData();
    const all_problem_num = dataTableRes.get('all_problem_num');
    const resolveNum = userRes.get('resolve_num');
    const submitNum = userRes.get('submit_num');

    //分析用户做题数据
    const userAnalyseInfo = {
      nickname: userRes.get('nickname'),
      level: userRes.get('level'),
      resolve_num: resolveNum,
      resolve_process: Math.floor(resolveNum / all_problem_num * 100) + '%',
      pass_rate: Math.floor(resolveNum / submitNum * 100) + '%',
      best_type: getAdvantageType(),
      disadvantage_type: getDisadvantageType()
    }

    //做题记录信息
    let recordsRes = await ResolveRecordService.findUserRecordsByUserId(userId);
    let recordsArr = [];

    // const problems = await ProblemService.getAllProblems();
    // const problemType = await ProblemTypeService.getAllProblemType();

    //逐个查
    for (var i = 0; i < recordsRes.length; i++) {
      const item = recordsRes[i];
      const title = (await ProblemService.findProblemById(item.pid)).get('title');
      const type = (await ProblemTypeService.findProblemTypeById(item.problemTypeId)).get('type_title')
      item.dataValues.title = title;
      item.dataValues.type = type;
      recordsArr.push(item.dataValues);
    }

    await ctx.render('user/user_center', {
      pageConf: pageConf.userCenter,
      commonPageConf,
      isLogin: ctx.session.userInfo ? true : false,
      curRouter: '/user/user-center',
      resolveRecord: recordsArr,
      userAnalyseInfo
    })
  }

}

module.exports = new UserController();